var path = require('path');
var express = require('express');
var http = require('http');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var winston = require('winston');
var expressWinston = require('express-winston');
var bodyParser = require('body-parser');
var config = require('./config');
var pkg = require('../package');
var routes = require("./routes");

var app = express();


app.use(express.static(path.join(__dirname, './upload/')));


//设置跨域访问
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// session 中间件
app.use(session({
    name: config.session.key,// 设置 cookie 中保存 session id 的字段名称
    secret: config.session.secret,// 通过设置 secret 来计算 hash 值并放在 cookie 中，使产生的 signedCookie 防篡改
    resave: true,// 强制更新 session
    saveUninitialized: false,// 设置为 false，强制创建一个 session，即使用户未登录
    cookie: {
        maxAge: config.session.maxAge// 过期时间，过期后 cookie 中的 session id 自动删除
    },
    store: new MongoStore({// 将 session 存储到 mongodb
        url: config.mongodb// mongodb 地址
    })
}));

app.use(bodyParser.json({
    limit: '200mb'
}));
app.use(bodyParser.urlencoded({
    limit: '200mb',
    extended: true
}));

// 正常请求的日志
app.use(expressWinston.logger({
    transports: [
        new winston.transports.Console({
            json: true,
            colorize: true
        }),
        new winston.transports.File({
            filename: path.join(__dirname, 'logs/success.log')
        })
    ]
}));
// 路由
routes(app);
// 错误请求的日志
app.use(expressWinston.errorLogger({
    transports: [
        new winston.transports.Console({
            json: true,
            colorize: true
        }),
        new winston.transports.File({
            filename: path.join(__dirname, 'logs/error.log')
        })
    ]
}));


var server = http.Server(app);

// 监听端口，启动程序
if (module.parent) {
    
    module.exports = server;
} else {

    // 监听端口，启动程序
    const port = process.env.PORT || config.port;
    server.listen(port, function () {
        console.log(`${pkg.name} listening on port ${port}`);
    });

}
